package com.lottery.utils.lobbyUtils.impl;

import com.lottery.dto.BetMessageDto;
import com.lottery.dto.PlaywayDto;
import com.lottery.dto.ResultDto;
import com.lottery.entity.*;
import com.lottery.initData.InitData;
import com.lottery.service.qiuqiu.lobbyService.LotteryDrawService;
import com.lottery.utils.DateUtil;
import com.lottery.utils.DealWithDouble;
import com.lottery.utils.lobbyUtils.PlaywayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class SscPlayutilImpl extends PlaywayUtil {
    // 下一次开奖的时间
    @Value("${SSCNEXTTIME}")
    private String SSCNEXTTIME;

    // 下一次开奖的期号
    @Value("${SSCNEXTEXPECT}")
    private String SSCNEXTEXPECT;


    @Override
    public boolean judgeBetTime() {
        // 获取开奖时间
        String nextTime = jedis.get(SSCNEXTTIME);

        int hours = new Date().getHours();
        int mins = new Date().getMinutes();
        if (hours < 9 || (hours == 9 && mins <= 40)) {
            return false;
        } else if (hours == 9 && mins > 40) {
            return true;
        } else {
            long openTime = 0;
            try {
                // 开奖前半分钟
                openTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(nextTime).getTime() - 1000 * 30;

            } catch (java.text.ParseException e) {
                logger.error("SscPlayutilImpl judgeBetTime error,{}", e);
                return false;
            }
            // 获取当前时间毫秒数
            long nowTime = System.currentTimeMillis();


            if (nowTime > openTime || !LotteryDrawService.sscbl) {
                return false;
            }
            return true;
        }
    }

    @Override
    protected void insertMessage(Integer lotteyType, Integer userId, List<PlaywayDto> list, String agencyMark, ResultDto result) {
        for (PlaywayDto py : list) {
            String mStr = py.getBettingRule() + "/" + py.getBettingMoney();
            msgNoticeService.insertBetNotice(userId, mStr, lotteyType, agencyMark,result);
        }
    }

    @Override
    protected AccountTransaction packageWaterInfo(Integer userId, double amount, String orderId) {
        Account account = accountDao.selectAccountByUserId(userId);
        String nextExpect = jedis.get(SSCNEXTEXPECT);
        AccountTransaction accountTransaction = new AccountTransaction();
        accountTransaction.setExpect(nextExpect);
        accountTransaction.setAccountId(account.getId());
        accountTransaction.setRemarks("[时时彩]期号["+nextExpect+"]下注");
        accountTransaction.setMoneyGo("下注");
        accountTransaction.setTransactionDate(new Date());
        accountTransaction.setTransactionMoney(amount);
        accountTransaction.setTransactionType(3);
        accountTransaction.setState(1);
        accountTransaction.setOrderId(orderId);
        accountTransaction.setAccountFunds(account.getAccountFunds());
        return accountTransaction;
    }

    @Override
    protected List<Bettinginfo> packageBetInfo(List<PlaywayDto> list, int userId, Integer lotteyType, ResultDto result) {
        String nextExpect = jedis.get(SSCNEXTEXPECT);
        List<Bettinginfo> bettinginfos = new ArrayList<>();
        List<BetMessageDto> betMessageDtos = new ArrayList<>();
        for (PlaywayDto py : list) {
            //更新账户余额数据;
            Account account = accountDao.selectAccountByUserId(userId);
            account.setAccountFunds(DealWithDouble.sub(account.getAccountFunds(), py.getBettingMoney(), 2, 4));
            account.setUserId(userId);
            accountDao.updateAccountById(account);
            //数据转存
            Bettinginfo bettinginfo = new Bettinginfo();
            bettinginfo.setAccountChange(DealWithDouble.sub(0, py.getBettingMoney(), 2, 4));
            bettinginfo.setAccountMoney(account.getAccountFunds());
            bettinginfo.setPlaywayinfoId(py.getPlaywayId());
            bettinginfo.setUserId(userId);
            bettinginfo.setLotteyType(lotteyType);
            bettinginfo.setBettingrule(py.getBettingRule());
            bettinginfo.setBettingnumber(py.getBettingMoney());
            bettinginfo.setExpect(nextExpect);
            bettinginfo.setRemark("期号["+nextExpect+"]未开奖");
            User user = userDao.selectId(userId);
            bettinginfo.setAgencyMark(user.getAgencyId());
            bettinginfo.setState(2);
            Date date = new Date();
            bettinginfo.setBettingDate(date);
            bettinginfo.setPayDate(date);
            // 查询playwayinfo表信息
            Playwayinfo playwayinfo = playwayinfoDao.selectPlaywayinfoById(py.getPlaywayId());
            bettinginfo.setPlaywayName(playwayinfo.getPlaywayName());
            int bettingmoney = playwayinfo.getEachMoney() * py.getBettingMoney();
            bettinginfo.setBettingmoney(bettingmoney);
            bettinginfos.add(bettinginfo);

            BetMessageDto msg = new BetMessageDto();
            msg.setBetMoney(bettinginfo.getBettingmoney() + "点");
            msg.setExpect(nextExpect);
            String betResult = msgDeal(py);
            //返回结果信息处理
            msg.setBetResult(betResult);
            betMessageDtos.add(msg);
        }
        result.setData3(lotteyType);
        result.setData2(DateUtil.getFormatDate("HH:mm:ss"));
        result.setList(betMessageDtos);
        return bettinginfos;
    }

    @Override
    public void insertTourBetData(List<PlaywayDto> list, Integer userId, Integer lotteyType, String agencyMark, ResultDto result) {
        double accountFunds = Double.parseDouble(jedis.hget(userId + "::" + lotteyType, "amount"));
        for (PlaywayDto py : list) {
            accountFunds = DealWithDouble.sub(accountFunds, py.getBettingMoney(), 2, 4);
        }
        if (accountFunds < 0) {
            result.setResultData(false, "你的金额不足", 8, null);
        } else {
            jedis.hset(userId + "::" + lotteyType, "amount", accountFunds + "");
            //将下注返回信息封装
            packageBetInfo(list, userId, lotteyType, result);
            insertMessage(lotteyType, userId, list, agencyMark, result);
        }
    }

    private String msgDeal(PlaywayDto py) {
        String result = "";
        Integer playwayId = py.getPlaywayId();
        Integer bettingMoney = py.getBettingMoney();
        String bettingRule = py.getBettingRule();
        String[] strings = bettingRule.split("/");
        switch (playwayId) {
            case 4:
                result = "第" + strings[0] + "球," + strings[1];
                break;
            case 5:
                result = "第" + strings[0] + "球,号码" + strings[1];
                break;
            case 6:
                if (strings.length > 1) {
                    result = "总和," + strings[1];
                } else {
                    result = "总和,区段" + strings[0];
                }
                break;
            case 7:
                result = "单码" + strings[1];
                break;
            case 8:
                result = strings[0];
                break;
            case 9:
                result = strings[0] + "," + strings[1];
                break;
        }
        result += ",点数" + bettingMoney;
        return result;
    }

    public static String getSscBetOdd(Integer playWayId, String betrule) {
        String result = "";
        String[] strings = betrule.split("/");
        switch (playWayId) {
            case 4:
                result = strings[1];
                break;
            case 5:
                result = strings[1];
                break;
            case 6:
                if (strings.length > 1) {
                    result = strings[1];
                } else {
                    result = strings[0];
                }
                break;
            case 7:
                result = strings[1];
                break;
            case 8:
                result = strings[0];
                break;
            case 9:
                result = strings[1];
                break;
        }
        return result;
    }

    public static PlaywayDto pacPlaywayInfo(String param, String agencyMark, Integer lotteyType) {
        PlaywayDto py = new PlaywayDto();
        int i = param.lastIndexOf("/");
        String betRule = param.substring(0, i);
        int betMoney = Integer.valueOf(param.substring(i + 1));
        if (InitData.SSC_BETRULE_REF_PLAYWAYID.containsKey(betRule)) {
            Integer playwayId = InitData.SSC_BETRULE_REF_PLAYWAYID.get(betRule);
            //7单码连码是个特殊情况,赔率map中存放方式特殊,做特殊处理
            String bet = "";
            if (playwayId != 7) {

                bet = getSscBetOdd(playwayId, betRule);
            }
            if (playwayId == 7 || InitData.LOTTEY_REF_LOTTEYODD.get(lotteyType).get(agencyMark).get(playwayId).containsKey(bet)) {
                py.setBettingMoney(betMoney);
                py.setBettingRule(betRule);
                py.setPlaywayId(playwayId);
                return py;
            } else {
                return null;
            }

        } else {
            return null;
        }
    }
}
